package com.itheima.app.manager;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.User;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangpeng
 */
@Component //加入springmvc容器
public class UserManager {
    @DubboReference
    private UserService userService;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    //保存用户
    public Long save(User user) {
        //设置一个初始化密码
        user.setPassword(ConstantUtil.INIT_PASSWORD);
        Long id = userService.save(user);
        return id;
    }

    //根据手机查询用户
    public User findByMobile(String mobile) {

        User user = userService.findByMobile(mobile);
        return user;
    }

    //发送手机验证码
    public void sendCode(String phone) {
        //1.生成随机验证码(6位数字验证码) ---使用hutool
        String code = RandomUtil.randomNumbers(6);
        //TODO 为了开发简单,发送固定的验证码"123456" ,等项目上线了,在发送随机的
        code = "123456";

        //2.调用smsTemplaate发送验证码到手机上面
        //TODO 项目上线了再把这行代码打开,
        //  smsTemplate.sendSms(phone, code);


        //3.将验证码存入到redis中,并设置时效为5分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone, code, Duration.ofMinutes(5));

    }

    //注册登录
    public ResponseEntity regAndLogin(Map<String, String> map) {
        //1.获取手机号和验证码
        String phone = map.get("phone");
        String verificationCode = map.get("verificationCode");


        //2.判断验证码和redis中是否相同,若不相同则返回错误提示
        //首先获取stringRedisTemplate 对象,获取redis中的验证码
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String redisCode = operations.get(ConstantUtil.SMS_CODE + phone);
        //使用hutools工具类,将输入的验证码与redisCode进行比较
        if (!StrUtil.equals(verificationCode, redisCode)) {
            // return ResponseEntity.status(500).body("请输入正确的验证码");
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
        //3.远程调用service,查询手机号是否存在
        User user = userService.findByMobile(phone);
        boolean isNew;
        //3.1 若存在,isNew = false
        if (user != null) {
            isNew = false;
        } else {
            //3.2 若不存在,isNew=true,封装user数据,保存到数据库中
            isNew = true;
            //创建user对象
            user = new User();
            user.setMobile(phone);
            user.setPassword(ConstantUtil.INIT_PASSWORD);
            Long id = userService.save(user);
            //别忘记给用户设置id
            user.setId(id);
        }
        //4.准备用户数据(id,手机号),生成token
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("id",user.getId());
        userMap.put("mobile",user.getMobile());
        //生成token
        String token = JwtUtil.createToken(userMap);
        //5.为了避免每次都解析token,将token作为key,用户的json数据做为value,放入redis中
        operations.set(ConstantUtil.USER_TOKEN+token, JSON.toJSONString(user),Duration.ofDays(30));

        //6.准备返回的数据(map),且返回
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("isNew",isNew);

        //7,建议把验证码删除
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE+phone);
        return ResponseEntity.ok(resultMap);


    }
}
